package com.guanghua.brick.html.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guanghua.brick.biz.ValidateException;

public class CoreCatchTag extends BodyTagSupport {
	
private static Log logger = LogFactory.getLog(CoreCatchTag.class);
	
	private Throwable exception = null;
	private String validateField = "";
	private String data = null;
	
	public int doStartTag() throws JspException {
		//初始化显示的数据
		data = (exception!=null)?exception.getMessage():"";
		if (validateField != null) {
			ValidateException ve = 
				(ValidateException)pageContext.getRequest().getAttribute(ValidateException.VE_KEY);
			if (ve != null)
				data = ve.get(validateField);
		}
		//放入attr中
		if (this.id != null)
			pageContext.getRequest().setAttribute(this.id, data);
		return BodyTagSupport.EVAL_BODY_INCLUDE;
	}
	
	
	public int doEndTag() throws JspException {
		try {
			String body = (bodyContent!=null)?bodyContent.getString():null;
			if (body != null) pageContext.getOut().write(data);
			else pageContext.getOut().write(data);
		} catch (IOException e) {
			logger.error("io exception on print catch tag", e);
		}
		
		//清除attr
		if (this.id != null) pageContext.getRequest().removeAttribute(this.id);
		return BodyTagSupport.EVAL_PAGE;
	}

	public Throwable getException() {
		return exception;
	}

	public void setException(Throwable exception) {
		this.exception = exception;
	}

	public String getValidateField() {
		return validateField;
	}

	public void setValidateField(String validateField) {
		this.validateField = validateField;
	}
}
